#!/bin/bash

# Docker 镜像构建和测试脚本
# 用于验证 Windows 兼容性问题是否已解决

echo "=========================================="
echo "  Docker 镜像构建和测试脚本"
echo "=========================================="

# 检查 Docker 和 Docker Compose 是否已安装
if ! command -v docker &> /dev/null; then
    echo "❌ Docker 未安装，请先安装 Docker"
    exit 1
fi

if ! command -v docker-compose &> /dev/null; then
    echo "❌ Docker Compose 未安装，请先安装 Docker Compose"
    exit 1
fi

echo "✅ Docker 和 Docker Compose 已安装"

# 停止现有容器
echo "🛑 停止现有容器..."
docker-compose down

# 清理旧镜像
echo "🧹 清理旧镜像..."
docker-compose build --no-cache

# 启动容器
echo "🚀 启动容器..."
docker-compose up -d

# 等待容器启动
echo "⏳ 等待容器启动（10秒）..."
sleep 10

# 检查容器状态
echo "📊 检查容器状态..."
if docker-compose ps | grep -q "Up"; then
    echo "✅ 容器已成功启动"
else
    echo "❌ 容器启动失败"
    echo "查看日志："
    docker-compose logs alpine-app
    exit 1
fi

# 测试 HTTP 服务
echo "🌐 测试 HTTP 服务..."
if curl -s http://localhost:8080 &> /dev/null; then
    echo "✅ HTTP 服务正常运行"
else
    echo "❌ HTTP 服务无法访问"
fi

# 测试脚本文件是否正常
echo "📝 测试脚本文件..."
if docker-compose exec -T alpine-app ls -la /app/app.sh &> /dev/null; then
    echo "✅ 主脚本文件存在"
else
    echo "❌ 主脚本文件不存在"
fi

# 测试定时任务
echo "⏰ 测试定时任务..."
if docker-compose exec -T alpine-app sudo crontab -l &> /dev/null; then
    echo "✅ 定时任务配置正常"
else
    echo "❌ 定时任务配置失败"
fi

# 测试 Python 脚本
echo "🐍 测试 Python 脚本..."
if docker-compose exec -T alpine-app python3 --version &> /dev/null; then
    echo "✅ Python 环境正常"
else
    echo "❌ Python 环境异常"
fi

# 显示系统信息
echo "📋 系统信息："
docker-compose exec -T alpine-app uname -a
docker-compose exec -T alpine-app whoami
docker-compose exec -T alpine-app python3 --version

echo "=========================================="
echo "🎉 测试完成！"
echo ""
echo "📝 有用的命令："
echo "   查看日志: docker-compose logs -f alpine-app"
echo "   进入容器: docker-compose exec alpine-app bash"
echo "   停止容器: docker-compose down"
echo "   重新构建: docker-compose build --no-cache"
echo "==========================================" 